package com.sap.health.tracker.threads;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sap.health.tracker.R;
import com.sap.health.tracker.json.JSONFunctions;
import com.sap.health.tracker.library.StoreData;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TableRow.LayoutParams;

/*
 * This class handles the connections that user have with each other.
 */
public class ConnectionsThread extends Activity {

	// JSON Response node names
    private static String KEY_SUCCESS = "success";
    private static String KEY_UID = "uid";
    private static String KEY_SESSION = "session";
    private static String KEY_ROLE = "role";   
    
    private String mUserType;
    private String mUserID;
    private String mSessionToken;
    private Context mCtx;
    private EditText mSearchInput;
    private TextView mGetPatientsErrorMsg; 
	private TableLayout mConnectionTable;
	private ProgressDialog mLoadingDialog;
    	
	/**
	 * Runs when Class is first created.
	 * @param ctx
	 * @param userId
	 * @param sessionToken
	 */
    public ConnectionsThread(Context ctx, String userId, String sessionToken,
    		final TextView getPatientsErrorMsg,  
    		final TableLayout connectionTable,
    		final ImageView refresh, 
    		final String state,
    		final EditText searchInput,
    		final Button search) {
    	
    	this.mGetPatientsErrorMsg = getPatientsErrorMsg;
    	this.mConnectionTable = connectionTable;
    	this.mSearchInput = searchInput;
    	this.mCtx = ctx;
    	this.mUserID = userId;
    	this.mSessionToken = sessionToken;
    	// used to tell the refresh function what to refresh.
    	this.mUserType = state;
    	// on long click, give the help dialog.
    	searchInput.setOnLongClickListener(new OnLongClickListener() { 
            @Override
            public boolean onLongClick(View v) {
                helpDialog("You can search for doctors or the hospitals they " +
                		"are associated with.");               	                	
                return true;
            }
        });
    	// on long click, give the help dialog.
    	search.setOnLongClickListener(new OnLongClickListener() { 
            @Override
            public boolean onLongClick(View v) {
                helpDialog("You can search for doctors or the hospitals they " +
                		"are associated with.");               	                	
                return true;
            }
        });
    	// add click listener to search for doctors.
    	search.setOnClickListener(new OnClickListener() {
         	public void onClick(View v) {
         		connectionTable.removeAllViews();
				if ("doctors".equalsIgnoreCase(state)){
	         		searchDoctors();
				}
         	}
         });
    	// refresh button.
    	refresh.setOnClickListener(new OnClickListener() {
         	public void onClick(View v) {
         		refresh();
         	}
        });	
    }

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // needed but not used  
    }
	/**
	 * Searches for doctors on it's own thread.
	 */
	private void searchDoctors(){		
		new Thread(new Runnable() {
    		@Override
            public void run() {
    			// tell the user it's busy.
            	showProgressDialog(); 
            	// get user input.
        		String input = mSearchInput.getText().toString();
        		// connect and get search from server.
                JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.searchDoctorsList(mUserID, 
                		mSessionToken, input);
                 // check for login response
                try {
                	if (json.getString(KEY_SUCCESS) != null) {
                		//hide error message from user.
                		emptyErrorMessage();
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){
                			final JSONArray doctors_list = 
                				json.getJSONArray("doctors_list");
                			// go through each doctor in the list and get the info.
                			for(int i = 0; i < doctors_list.length(); i++){
                				String doctorId = doctors_list.getJSONObject(i).
                						getString("user_id");
                				String firstname = doctors_list.getJSONObject(i).
                						getString("user_firstname");
                				String lastname = doctors_list.getJSONObject(i).
                						getString("user_lastname");
                				String gender = doctors_list.getJSONObject(i).
                						getString("user_gender");
                				String email = doctors_list.getJSONObject(i).
                						getString("user_email");
                				String contact = doctors_list.getJSONObject(i).
                						getString("user_contact");
                				String speciality = doctors_list.getJSONObject(i)
                						.getString("doctor_speciality");
                				String regno = doctors_list.getJSONObject(i).
                						getString("doctor_regno");
                				String hospitalname = doctors_list.
                					getJSONObject(i).getString("hospital_name");
                				
                				String pending = null;
                				// For doctors, this will be null.
                				if(!doctors_list.getJSONObject(i).
                						isNull("pending")){
                					System.out.println("Is Not Null");
                					pending = doctors_list.getJSONObject(i).
                							getString("pending");
                				}
                    			// pass each doctors info to UI handler.
                				doctorsUiHandler(doctorId, firstname, lastname, 
                						gender, email, contact, speciality, 
                						regno, pending, hospitalname);                           
                			}
         
                		} else if(Integer.parseInt(res) == 2){
                			// List is empty
                			errorMessage("No search results");
                                                         
                		}else{
                			//let the user know there was an error.
       		        	 	errorMessage("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                	 //TODO better exception handling.
                     e.printStackTrace();
                     // let the user know there was an error.
		        	 errorMessage("Network Connection Error");		        	 
                 }
                 hideProgressDialog();
    		}                  	
    	}).start();			
	}
	/**
	 * Get the lest of all the doctors registered.
	 */
	public void getDoctors(){	
    	new Thread(new Runnable() {
    		@Override
            public void run() {
    			// tell the user it's busy.
            	showProgressDialog();
            	// connect to server and get list.
                JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.getDoctorsList(mUserID, 
                		mSessionToken);
                // check for login response
                try {
                	if (json.getString(KEY_SUCCESS) != null) {
                		//hide error message from user.
                		emptyErrorMessage();        		
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){
                			// user successfully logged in
                			final JSONArray doctors_list = json.getJSONArray("doctors_list");
                			// sort through each doctor and get their details.
                			for(int i = 0; i < doctors_list.length(); i++){
                				String doctorId = doctors_list.getJSONObject(i).
                						getString("user_id");
                				String firstname = doctors_list.getJSONObject(i)
                						.getString("user_firstname");
                				String lastname = doctors_list.getJSONObject(i).
                						getString("user_lastname");
                				String gender = doctors_list.getJSONObject(i).
                						getString("user_gender");
                				String email = doctors_list.getJSONObject(i).
                						getString("user_email");
                				String contact = doctors_list.getJSONObject(i).
                						getString("user_contact");
                				String speciality = doctors_list.getJSONObject(i)
                						.getString("doctor_speciality");
                				String regno = doctors_list.getJSONObject(i).
                						getString("doctor_regno");
                				String hospitalname = doctors_list.
                					getJSONObject(i).getString("hospital_name");
                				
                				String pending = null;
                				// For doctors, this will be null
                				if(!doctors_list.getJSONObject(i).
                						isNull("pending")){
                					pending = doctors_list.getJSONObject(i).
                							getString("pending");
                				}
                    			// pass doctor details to UI handler.
                				doctorsUiHandler(doctorId, firstname, lastname, 
                						gender, email, contact, speciality, 
                						regno, pending, hospitalname);                           
                			}
                                              
                		} else if(Integer.parseInt(res) == 2){
                			// List is empty
                			errorMessage("There are no doctors registered.");
                                                         
                		}else{
                			//let the user know there was an error.
       		        	 	errorMessage("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                     // let the user know there was an error.
		        	 errorMessage("Network Connection Error");		        	 
                 }
                 hideProgressDialog();
    		}                  	
    	}).start();		
    }
	/**
	 * Get the connections that the user is connected to.
	 */
    public void getConnections(){   	
    	new Thread(new Runnable() {
    		@Override
            public void run() {
    			// tell the user it's busy.
            	showProgressDialog();
            	// connect to server and get connections.
                JSONFunctions userFunction = new JSONFunctions();         
                JSONObject json = userFunction.getConnectionList(mUserID, 
                		mSessionToken);               
                // check for login response
                try {
                	if (json.getString(KEY_SUCCESS) != null) {
                		//hide error message from user.
                		emptyErrorMessage();              		
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){
                			// user successfully logged in
                			final JSONArray json_connection_list = 
                				json.getJSONArray("connectionList");
                			// pass connection list to UI handler.                             
                			for(int i = 0; i < json_connection_list.length(); i++){
                				StoreData store = new StoreData();
                				store.openType(mCtx, String.class, KEY_ROLE); 
                		        connectionsUiHandler(json_connection_list.
                		        		getJSONObject(i));                           
                			}                                                        
                		} else if(Integer.parseInt(res) == 2){
                			// List is empty
                			errorMessage("You currently have no connections.");                                                        
                		}else{
                			//let the user know there was an error.
       		        	 	errorMessage("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                     // let the user know there was an error.
		        	 errorMessage("Network Connection Error");		        	 
                 }
                 hideProgressDialog();
    		}                  	
    	}).start();		
    }  
    /**
     * Add a doctor as a connection for the patient.
     * @param patient_ID
     * @param dialog
     * @param noteDialog
     * @param note
     */
    private void addDoctor(
    		final String patient_ID, 
    		final Dialog dialog, 
    		final Dialog noteDialog, 
    		final String note){
    	new Thread(new Runnable() {
            @Override
            public void run() {
            	// show user it's busy.
            	showProgressDialog();
            	// connect to server and add doctor.
            	JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.addDoctor(mUserID, mSessionToken,
                		patient_ID, note);          	
                try {
                	if (json.getString(KEY_SUCCESS) != null) {
                		//turn of error message.
                		emptyErrorMessage();
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){
                			System.out.println("Doctor Added");
                			dialog.dismiss();
                			noteDialog.dismiss();
                			refresh();             			          			
                		}else{
                			//let the user know there was an error.
       		        	 	simpleDialog("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                	 //TODO better exception handling.
                     e.printStackTrace();
		        	 simpleDialog("Network Connection Error");
                 }                             
            	hideProgressDialog();
            }
    	}).start();
    }
    /**
     * Remove a doctor that is connected to a patient.
     * @param patient_ID
     * @param dialog
     */
    private void removeDoctor(final String patient_ID, final Dialog dialog){
    	new Thread(new Runnable() {
            @Override
            public void run() {
            	// tell the user it's busy.
            	showProgressDialog();
            	// connect to server and remove doctor.
            	JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.removeDoctor(mUserID, 
                		mSessionToken, patient_ID);          	
                try {
                	if (json.getString(KEY_SUCCESS) != null) {
                		//turn of error message.
                		emptyErrorMessage();
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){
                			dialog.dismiss(); 
                			refresh();             			          			
                		}else{
                			//let the user know there was an error.
       		        	 	simpleDialog("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                	 //TODO better exception handling.
                     e.printStackTrace();
		        	 simpleDialog("Network Connection Error");
                 }                             
            	hideProgressDialog();
            }
    	}).start();
    }
    /**
     * Accept a patients request to connect to the doctor.
     * @param patient_ID
     * @param dialog
     */
    private void acceptPatient(final String patient_ID, final Dialog dialog){
    	new Thread(new Runnable() {
            @Override
            public void run() {
            	// let the user know it's busy.
            	showProgressDialog();
            	// connect to the server and accept patient.
            	JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.acceptPatient(mUserID,
                		mSessionToken, patient_ID);         	
                try {
                	if (json.getString(KEY_SUCCESS) != null) {
                		//turn of error message.
                		emptyErrorMessage();
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){
                			dialog.dismiss(); 
                			refresh();             			          			
                		}else{
                			//let the user know there was an error.
       		        	 	simpleDialog("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                	 //TODO better exception handling.
                     e.printStackTrace();
		        	 simpleDialog("Network Connection Error");
                 }                             
            	hideProgressDialog();
            }
    	}).start();
    }
    /**
     * Remove patient from doctors connections.
     * @param patient_ID
     * @param dialog
     */
    private void removePatient(final String patient_ID, final Dialog dialog){
    	new Thread(new Runnable() {
            @Override
            public void run() {
            	// let the user know it's busy.
            	showProgressDialog();
            	// connect to server and remove patient.
            	JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.removePatientFrom(mUserID, 
                		mSessionToken, patient_ID);         	
                try {
                	if (json.getString(KEY_SUCCESS) != null) {
                		//turn of error message.
                		emptyErrorMessage();
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){
                			dialog.dismiss();
                			refresh();               			          			
                		}else{
                			//let the user know there was an error.
       		        	 	simpleDialog("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                	 //TODO better exception handling.
                     e.printStackTrace();
		        	 simpleDialog("Network Connection Error");
                 }                             
            	hideProgressDialog();
            }
    	}).start();
    }
    /**
     * A simple dialog to display to the user with a message.
     * @param title
     */
    private void simpleDialog(final String title){
    	runOnUiThread(new Runnable() {
			public void run() {
				// new dialog.
				final Dialog dialog = new Dialog(mCtx);
				dialog.setContentView(R.layout.popup);
				dialog.setTitle(title);	 	
				Button dialogButton = (Button) dialog.findViewById(R.id.dismiss);
				// if button is clicked, close the custom dialog
				dialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
		 
				dialog.show();
			}
		}); 
		
	}
    /**
     * Handles a individual Doctors UI information.
     * @param doctorId
     * @param user_firstname
     * @param user_lastname
     * @param gender
     * @param email
     * @param contact
     * @param speciality
     * @param regno
     * @param pending
     * @param hospitalName
     */
    private void doctorsUiHandler(
    		final String doctorId, 
    		final String user_firstname, 
    		final String user_lastname, 
    		final String gender, 
    		final String email,
    		final String contact,
    		final String speciality,
    		final String regno, 
    		final String pending,
    		final String hospitalName){
    	
    	runOnUiThread(new Runnable() {
    		public void run() {
    			// declare a new row
               	TableRow nameRow = new TableRow(mCtx);
               	// create text view.
               	TextView nameTx = new TextView(mCtx);              	
               	TableRow hospitalNameRow = new TableRow(mCtx);
               	TextView hospitalNameTx = new TextView(mCtx);               	 
               	 
               	hospitalNameTx.setText("Hosptial: " + hospitalName);
               	hospitalNameTx.setTextColor(Color.parseColor("#C4C4C4"));               	 
               	hospitalNameRow.addView(hospitalNameTx);
               	hospitalNameRow.setPadding(20, 0, 0, 10);
     
               	boolean connectionStatus = false;
                TableLayout containerRow = new TableLayout(mCtx);
                // if null, then not conencted.
           		if(pending == null){
           			nameTx.setText(user_firstname + " " + user_lastname);
           			// Help dialog.
           			containerRow.setOnLongClickListener(new OnLongClickListener() { 
	           			@Override
	                    public boolean onLongClick(View v) {
	                        helpDialog("You can add or remove a Doctor from your " +
	                        		"connections list.\n\n" +
	                        		"WARNING: Once you are connected with a " +
	                        		"Doctor, they will be able to view your " +
	                        		"profile and your log data. ");               	                	
	                        return true;
	                    }
           			});              		
               	} else if("accepted".equalsIgnoreCase(pending)){
               		// ^ user is connected.
               		nameTx.setText(user_firstname + " " + user_lastname + " " + 
               				"is connected");  
                   	connectionStatus = true;                	 
                   	containerRow.setOnLongClickListener(new OnLongClickListener() { 
                        @Override
                        public boolean onLongClick(View v) {
                            helpDialog("You can add or remove a Doctor from your " +
                            		"connections list.\n\n" +
                            		"You are currently connected with this person.");               	                	
                            return true;
                        }
                    });
               	} else if ("waiting".equalsIgnoreCase(pending)){
               		 // ^ waiting for a connection.
               		 nameTx.setText(user_firstname + " " + user_lastname + 
               				 " is considering your request.");  
                  	 connectionStatus = true;               	
                  	 containerRow.setOnLongClickListener(new OnLongClickListener() { 
                        @Override
                        public boolean onLongClick(View v) {
                            helpDialog("You can add or remove a Doctor from your " +
                            		"connections list.\n\n" +
                            		"You are currently waiting for this person " +
                            		"to connect with you.");               	                	
                            return true;
                        }
                    });
               	} else { 
               		// placeholder in case pending is something else.
               		nameTx.setText(user_firstname + " " + user_lastname);               		
               		containerRow.setOnLongClickListener(new OnLongClickListener() { 
                        @Override
                        public boolean onLongClick(View v) {
                            helpDialog("You can add or remove a Doctor from your " +
                            		"connections list.\n\n" +
                            		"WARNING: Once you are connected with a " +
                            		"Doctor, they will be able to view your " +
                            		"profile and your log data. ");               	                	
                            return true;
                        }
                    });
               	 }              	 
               	 nameTx.setLayoutParams(new TableRow.LayoutParams(LayoutParams.
               			 WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
               	 nameTx.setTextSize(18f);
               	 // add views to the row
               	 nameRow.addView(nameTx);  
               	 nameRow.setPadding(20, 10, 0, 0);              	               	
               	 
               	 containerRow.addView(nameRow);
               	 containerRow.addView(hospitalNameRow);
               	
               	 // must pass to final 
              	 final boolean connectionPass = connectionStatus;
              	 // when user clicks on it, a profile pops up.
              	 containerRow.setOnClickListener(new View.OnClickListener() {
              		 public void onClick(View v) {
              			 doctorDialog(R.layout.popup, doctorId, user_firstname, 
              					 user_lastname, gender, email, contact,speciality, 
              					 regno, connectionPass, hospitalName);                     
              		 }
              	 });             	
               	 
               	 // add the row to the table layout
               	 mConnectionTable.addView(containerRow);             	 
               	 // Used for creating a horizontal line to separate .             	  
               	 View ruler = new View(mCtx); ruler.setBackgroundColor(0xFFDEDEDE);
               	 mConnectionTable.addView(ruler, new ViewGroup.LayoutParams( 
               			 ViewGroup.LayoutParams.MATCH_PARENT, 2));         	 
            }
        });
    }
    /**
     * Connections UI handler.
     * @param fields
     */
    private void connectionsUiHandler(final JSONObject fields){  	
    	runOnUiThread(new Runnable() {
            public void run() {
            	// declare a new row
               	TableRow nameRow = new TableRow(mCtx);
               	// create text view.
               	TextView nameTx = new TextView(mCtx);
               	nameTx.setTextSize(18f);
               	// determines if connected or not.
               	boolean connectionStatus = false;
               	try {
               		if("accepted".equalsIgnoreCase(fields.getString("pending"))){
               			nameTx.setText(fields.getString("connection_name"));  
					   	connectionStatus = true;					   	 					   	 
					} else {
						StoreData store = new StoreData();
					    if("doctor".equals(store.openType(mCtx, String.class, 
					    		KEY_ROLE))){
					      	nameTx.setText(fields.getString("connection_name") + 
					      			" has sent a connection request.");
					    } else {
					       	nameTx.setText(fields.getString("connection_name") + 
					       			" is considering your request.");
					    }
					}
				} catch (JSONException e) {
					//let the user know there was an error.
		        	simpleDialog("Internal Error");
				}
               	nameTx.setLayoutParams(new TableRow.LayoutParams(
               			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	                	 
               	// add views to the row
               	nameRow.addView(nameTx);
               	nameRow.setPadding(10, 10, 0, 10);
               	 
               	// must pass to final 
               	final boolean connectionPass = connectionStatus;
               	nameRow.setOnClickListener(new View.OnClickListener() {
               		public void onClick(View v) {
                    	patientDialog(R.layout.popup, fields, connectionPass);          	
                    }
                }); 
            	// help dialog.
               	nameRow.setOnLongClickListener(new OnLongClickListener() { 
                    @Override
                    public boolean onLongClick(View v) {
                        helpDialog("These are your current connections.");               	                	
                        return true;
                    }
                });
               	// add the row to the table layout
               	mConnectionTable.addView(nameRow);              	 
             	//Used for creating a horizontal line to separate .             	
               	View ruler = new View(mCtx); ruler.setBackgroundColor(0xFFDEDEDE);
               	mConnectionTable.addView(ruler, new ViewGroup.LayoutParams(
               			ViewGroup.LayoutParams.MATCH_PARENT, 2));           	 
            }
        });
    }
    /**
     * Dialog for viewing doctor profile info.
     * @param itemsPopup
     * @param doctorId
     * @param firstname
     * @param lastname
     * @param gender
     * @param email
     * @param contact
     * @param speciality
     * @param regno
     * @param connectionStatus
     * @param hospitalName
     */
    private void doctorDialog(
    		int itemsPopup, 
    		final String doctorId, 
    		final String firstname,
    		final String lastname, 
    		final String gender,
    		final String email,
    		final String contact, 
    		final String speciality,
    		final String regno,
    		final boolean connectionStatus, 
    		final String hospitalName){
    	
    	// new dialog.
		final Dialog dialog = new Dialog(mCtx);
		dialog.setContentView(itemsPopup);
		dialog.setTitle(firstname + " " + lastname);
		//create rows
		TableRow genderRow = new TableRow(mCtx);
		TableRow emailRow = new TableRow(mCtx);
		TableRow contactRow = new TableRow(mCtx);
		TableRow specialityRow = new TableRow(mCtx);
		TableRow regnoRow = new TableRow(mCtx);
		TableRow hospitalRow = new TableRow(mCtx);
		// create text view.
		TextView genderTx = new TextView(mCtx);
		TextView emailTx = new TextView(mCtx);
		TextView contactTx = new TextView(mCtx);
		TextView specialityTx = new TextView(mCtx);
		TextView regnoTx = new TextView(mCtx);
		TextView hospitalTx = new TextView(mCtx);
		// wrap text
		genderTx.setLayoutParams(new TableRow.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
		emailTx.setLayoutParams(new TableRow.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
		contactTx.setLayoutParams(new TableRow.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
		specialityTx.setLayoutParams(new TableRow.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
		regnoTx.setLayoutParams(new TableRow.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
		hospitalTx.setLayoutParams(new TableRow.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
		// set text
     	genderTx.setText("Gender: " + gender);
     	emailTx.setText("Email: " + email);
     	contactTx.setText("Contact: " + contact);
     	specialityTx.setText("Speciality: " + speciality);
     	regnoTx.setText("Registration Number: " + regno);
		hospitalTx.setText("Hospital: " + hospitalName);
      	// add views to the row
     	genderRow.addView(genderTx);
		emailRow.addView(emailTx);
		contactRow.addView(contactTx);
		specialityRow.addView(specialityTx);
		regnoRow.addView(regnoTx);
		hospitalRow.addView(hospitalTx);
		// add padding
		genderRow.setPadding(10, 20, 0, 0);
		emailRow.setPadding(10, 20, 0, 0);
		contactRow.setPadding(10, 20, 0, 0);
		specialityRow.setPadding(10, 20, 0, 0);
		regnoRow.setPadding(10, 20, 0, 0);
		hospitalRow.setPadding(10, 20, 0, 0);
		// create table.
      	TableLayout dialogTable = (TableLayout) dialog.findViewById(
      			R.id.dialogTable);          
      	// add the row to the table layout
      	dialogTable.addView(genderRow);
      	dialogTable.addView(emailRow);
      	dialogTable.addView(contactRow);
      	dialogTable.addView(specialityRow);
      	dialogTable.addView(regnoRow);
      	dialogTable.addView(hospitalRow);
    	// open local storage.
      	StoreData store = new StoreData();     	
      	// if patient is connected to the doctor, have add and remove options.
      	if("patient".equals(store.openType(mCtx, String.class, KEY_ROLE))){
	      	if(connectionStatus){
	      		// always have remove button.
		      	Button remove = new Button(mCtx);
		      	remove.setText("Remove");
		      	TableLayout btnTable = (TableLayout) dialog.findViewById(
		      			R.id.btnTable);    
		      	btnTable.addView(remove);		      	
				// if button is clicked, close the custom dialog
				remove.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						System.out.println("Remove Hospital");
						removeDoctor(doctorId, dialog);
					}
				});
			} else {
				Button add = new Button(mCtx);
				add.setText("Add");
		      	TableLayout btnTable = (TableLayout) dialog.findViewById(
		      			R.id.btnTable);    
		      	btnTable.addView(add);		      	
		      	// if button is clicked, close the custom dialog
				add.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {						
						// Show dialog that requests to add a note.
        				final Dialog noteDialog = new Dialog(mCtx);
        				noteDialog.setContentView(R.layout.popup);
        				noteDialog.setTitle("Add " + firstname + " " + lastname);
        				
        				Button add = new Button(mCtx);
        				add.setText("Add Doctor");
        		      	TableLayout btnTable = 
        		      		(TableLayout) noteDialog.findViewById(R.id.btnTable);    
        		      	btnTable.addView(add);
        		      	        		      	
        		      	final EditText note = new EditText(mCtx);
        		      	note.setLines(4);
        		      	note.setHint("Send a note (optional).");
        		      	btnTable.addView(note); 		      	
        				// if button is clicked, add doctor
        				add.setOnClickListener(new OnClickListener() {
        					@Override
        					public void onClick(View v) {					
        						addDoctor(doctorId, dialog, noteDialog,
        								note.getText().toString());       				        
        					}
        				});        				
        				Button dialogNoteButton = 
        					(Button) noteDialog.findViewById(R.id.dismiss);
        				// if button is clicked, close the custom dialog
        				dialogNoteButton.setOnClickListener(new OnClickListener() {
        					@Override
        					public void onClick(View v) {
        						noteDialog.dismiss();
        					}
        				});     		 
        				noteDialog.show();			        
					}
				});		
				
			}
      	}      	      	      	
		Button dialogButton = (Button) dialog.findViewById(R.id.dismiss);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}
    /**
     * Handles adding stuff to the dialog for viewing patient profile.
     * @param dialogTable
     * @param fields
     */
    private void patientProfile(TableLayout dialogTable, final JSONObject fields){
    	try{
    		//make sure the table is clear.
    		dialogTable.removeAllViews();
	    	TableRow emailRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView emailTx = new TextView(mCtx);
	      	emailTx.setText("Email: " + fields.getString("email"));
	      	emailTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 

	      	// add views to the row
	      	emailRow.addView(emailTx);
	      	emailRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(emailRow);
	      	
	    	TableRow genderRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView genderTx = new TextView(mCtx);
	      	genderTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 

	      	genderTx.setText("Gender: " + asUpperCaseFirstChar(
	      			fields.getString("gender")));
	      	// add views to the row
	      	genderRow.addView(genderTx);
	      	genderRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(genderRow);
	
	
	      	TableRow contactRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView contactTx = new TextView(mCtx);
	      	contactTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 

	      	contactTx.setText("Contact: " + fields.getString("contact"));
	      	// add views to the row
	      	contactRow.addView(contactTx);
	      	contactRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(contactRow);
	
	      	TableRow dobRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView dobTx = new TextView(mCtx);
	      	dobTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 

	      	dobTx.setText("Date of Birth: " + fields.getString("dob"));
	      	// add views to the row
	      	dobRow.addView(dobTx);
	      	dobRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(dobRow);
	
	      	TableRow bloodRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView bloodTx = new TextView(mCtx);
	      	bloodTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 

	      	bloodTx.setText("Blood Type: " + fields.getString("blood_type"));
	      	// add views to the row
	      	bloodRow.addView(bloodTx);
	      	bloodRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(bloodRow);
	
	      	TableRow allergyRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView allergyTx = new TextView(mCtx);
	      	allergyTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 

	      	allergyTx.setText("Allergies: " + fields.getString("allergy"));
	      	// add views to the row
	      	allergyRow.addView(allergyTx);
	      	allergyRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(allergyRow);
    	} catch (Exception e) {
    		//TODO better exception handling.
    		System.out.println("Failed to view patient profile: " + e);
    	}
    }
    /**
     * View doctor profile.
     * @param dialogTable
     * @param fields
     */
    private void doctorProfile(TableLayout dialogTable, final JSONObject fields){
    	try{
    		//make sure the table is clear.
    		dialogTable.removeAllViews();
	    	TableRow emailRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView emailTx = new TextView(mCtx);
	      	emailTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
	      	emailTx.setText("Email: " + fields.getString("email"));
	      	// add views to the row
	      	emailRow.addView(emailTx);
	      	emailRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(emailRow);
	      	
	    	TableRow genderRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView genderTx = new TextView(mCtx);
	      	genderTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
	      	genderTx.setText("Gender: " + fields.getString("gender"));
	      	// add views to the row
	      	genderRow.addView(genderTx);
	      	genderRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(genderRow);
	
	      	TableRow contactRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView contactTx = new TextView(mCtx);
	      	contactTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
	      	contactTx.setText("Contact: " + fields.getString("contact"));
	      	// add views to the row
	      	contactRow.addView(contactTx);
	      	contactRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(contactRow);
	      	
	      	TableRow specialityRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView specialityTx = new TextView(mCtx);
	      	specialityTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
	      	specialityTx.setText("Speciality: " + fields.getString("speciality"));
	      	// add views to the row
	      	specialityRow.addView(specialityTx);
	      	specialityRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(specialityRow);
	      	
	      	TableRow regRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView regTx = new TextView(mCtx);
	      	regTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
	      	regTx.setText("Regristration Number: " + fields.getString("speciality"));
	      	// add views to the row
	      	regRow.addView(regTx);
	      	regRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(regRow);
	      	
	      	TableRow hospitalRow = new TableRow(mCtx);
	      	// create text view.
	      	TextView hospitalTx = new TextView(mCtx);
	      	hospitalTx.setLayoutParams(new TableRow.LayoutParams(
	      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 

	      	String hospitalNames = "";
	      	for(int i = 0; i < fields.getJSONArray("hospital").length(); i++){
	      		hospitalNames += fields.getJSONArray("hospital").
	      				getJSONObject(i).getString("hospital_name");
	      		if(i != fields.getJSONArray("hospital").length() - 1){
	      			hospitalNames += ", ";
	      		}
	      	}     
	      	
	      	hospitalTx.setText("Hospital: " + hospitalNames);
	      	// add views to the row
	      	hospitalRow.addView(hospitalTx);
	      	hospitalRow.setPadding(10, 10, 0, 10);
	      	dialogTable.addView(hospitalRow);
    	} catch (Exception e){
    		//TODO better exception handling
    		System.out.println("Failed to view Doctor profile: " + e);
    	}
    }
    
    /**
     * Patients dialog setup.
     * @param itemsPopup
     * @param fields
     * @param connectionStatus
     */
    private void patientDialog(
    		int itemsPopup, 
    		final JSONObject fields, 
    		final Boolean connectionStatus){  	    	
    	try{
	    	// new dialog
			final Dialog dialog = new Dialog(mCtx);
			dialog.setContentView(itemsPopup);
			dialog.setTitle(fields.getString("connection_name"));
	    	// new table
	     	final TableLayout dialogTable = 
	     		(TableLayout) dialog.findViewById(R.id.dialogTable);    	     	
			// open connection to local storage.
	    	StoreData store = new StoreData();
		    // get the role the user is.
		    String role = (String) store.openType(mCtx, String.class, KEY_ROLE);		    
		    // if the user is a doctor and is connected, allow him to view persons logdata.
	      	if(connectionStatus && "doctor".equals(
	      			store.openType(mCtx, String.class, KEY_ROLE))){	      		
	      		// add catagories to array.
	      		ArrayList<String> catagories = new ArrayList<String>();
	      		catagories.add("Profile");
	      		catagories.add("Data Log History");
	      		catagories.add("Food");
	      		catagories.add("Symptoms");
	      		// get spinner from dialog layout
	      		Spinner catagoriesSpin = 
	      			(Spinner)dialog.findViewById(R.id.catagories);
	      		catagoriesSpin.setVisibility(View.VISIBLE);	      		
	      		//create adaptor and add the string values to it.
	      		ArrayAdapter<String >catagoriesAdapter = 
	      			new ArrayAdapter<String>(mCtx,
        	    		android.R.layout.simple_spinner_item, catagories);  	    
        	    // Specify the layout to use when the list of choices appears
	      		catagoriesAdapter.setDropDownViewResource(
	      				android.R.layout.simple_spinner_dropdown_item);    
        	    // Apply the adapter to the spinner
        	    catagoriesSpin.setAdapter(catagoriesAdapter);
        	    // set listener.
        	    catagoriesSpin.setOnItemSelectedListener(
        	    		new OnItemSelectedListener() {
	        	    @Override
	        	    public void onItemSelected(AdapterView<?> parentView, 
	        	    		View selectedItemView, int position, long id) {
	        	    	switch(position){
	        	    	case 0:
	        	    		// show patient profile.
	        		    	patientProfile(dialogTable, fields);
	        		    	break;
	        	    	case 1:
	        	    		getPatientLog(dialogTable, fields);
	        	    		break;
	        	    	case 2:
	        	    		getPatientFoodLog(dialogTable, fields);
	        	    		break;
	        	    	case 3:
	        	    		getSymptoms(dialogTable, fields);
	        	    		break;
	        	    	default:
		        	    	patientProfile(dialogTable, fields);
	        	    		break;
	        	    	}        	    	
	        	    }
	        	    @Override
	        	    public void onNothingSelected(AdapterView<?> parentView) {
	        	        // your code here
	        	    }                   		        
				});
	      		
			} else if("doctor".equals(role)){
		    	// show patient profile.
		    	patientProfile(dialogTable, fields);			    	
		    } else if("patient".equals(role)){
		    	//show doctor profile.
	    		doctorProfile(dialogTable, fields);
		    }		    	     		    	    
	      	// if we have not accepted the request yet, place an add button (only if a doctor).
	      	if(!connectionStatus && "doctor".equals(
	      			store.openType(mCtx, String.class, KEY_ROLE))){
	      		Button add = new Button(mCtx);
				add.setText("Accept");
		      	TableLayout btnTable = 
		      		(TableLayout) dialog.findViewById(R.id.btnTable);    
		      	btnTable.addView(add);		      	
				// if button is clicked, close the custom dialog
				add.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						try {
							acceptPatient(fields.getString("connection_id"),
									dialog);
						} catch (Exception e) {
							//TODO better exception handling.
							//let the user know there was an error.
		                     e.printStackTrace();
				       	 	simpleDialog("Internal Error");
						}			        
					}
				});
			} 
	      	
	      	// always have remove button.
	      	Button remove = new Button(mCtx);
	      	remove.setText("Remove");
	      	TableLayout btnTable = 
	      		(TableLayout) dialog.findViewById(R.id.btnTable);    
	      	btnTable.addView(remove);      	
			// if button is clicked, close the dialog
			remove.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					System.out.println("Remove Hospital");
					try {
						removePatient(fields.getString("connection_id"), dialog);
					} catch (Exception e) {
						//TODO better exception handling.
						//let the user know there was an error.
	                     e.printStackTrace();
			       	 	simpleDialog("Internal Error");
					}
				}
			});	      	
			Button dialogButton = (Button) dialog.findViewById(R.id.dismiss);
			// if button is clicked, close the custom dialog
			dialogButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
	
			dialog.show();
    	} catch (Exception e){
    		//TODO better exception handling.
    		//let the user know there was an error.
            e.printStackTrace();
       	 	simpleDialog("Internal Error");
    	}
		
	}
    /**
     * Get the food log for the patient.
     * @param dialogTable
     * @param fields
     */
    public void getPatientFoodLog(
    		final TableLayout dialogTable, 
    		final JSONObject fields){     
    	new Thread(new Runnable() {
    		@Override
            public void run() {
            	showProgressDialog();          	
            	runOnUiThread(new Runnable() {
                    public void run() {
                    	// clear the table first
                        dialogTable.removeAllViews();           
                    }
                });            	
            	// get data from local storage.
                StoreData store = new StoreData();
                // get user id from local storage
                mUserID = (String) store.openType(mCtx, String.class, KEY_UID);
                // get session token from local storage
                mSessionToken = (String) store.openType(mCtx, String.class, KEY_SESSION);           	
                try {
                	// connect to server and get the food list.
                	JSONFunctions userFunction = new JSONFunctions();
                	JSONObject json = userFunction.getFood(
                			mUserID, mSessionToken, fields.getString("connection_id"));                                          
                	// check for login response               
                	if (json.getString(KEY_SUCCESS) != null) {
                		//hide error message from user.
                		emptyErrorMessage();
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){
                			if(!json.isNull("foodList")){
	                			JSONArray jsonLogs = json.getJSONArray("foodList");              			         			
	                			// go through and get the details of each food.
	                			for(int i = jsonLogs.length() - 1; i >= 0; i--){
	                				String name = jsonLogs.getJSONObject(i).getString("food_name");
	                				String value = jsonLogs.getJSONObject(i).getString("food_calories");
	                				jsonLogs.getJSONObject(i).getString("food_note");
	                				jsonLogs.getJSONObject(i).getString("food_id");
	                				patientsDataLog(name, value, dialogTable);
	                			}   
                			} else {
                                simpleDialog("No data logged.");
                			}
	            			
                		}else{
                			//let the user know there was an error.
                            simpleDialog("Error Accessing Database.");
                		}                		
                     }
                 } catch (Exception e) {
                	 //TODO better exception handling.
                     e.printStackTrace();
                     // let the user know there was an error.
                     simpleDialog("Network Connection Error.");
                 }
                 hideProgressDialog();
    		}                  	
    	}).start();		
    }   
    /**
     * Get the symptoms logs for the patient.
     * @param dialogTable
     * @param fields
     */
    public void getSymptoms(final TableLayout dialogTable, final JSONObject fields){        
    	new Thread(new Runnable() {
    		@Override
            public void run() {
    			//show the progress dialog.
            	showProgressDialog();
            	// clear the table first.
            	runOnUiThread(new Runnable() {
                    public void run() {
                    	// clear the table first
                    	dialogTable.removeAllViews();            
                    }
                });           	
            	// get data from local storage.
                StoreData store = new StoreData();
                // get user id from local storage
                mUserID = (String) store.openType(mCtx, String.class, KEY_UID);
                // get session token from local storage
                mSessionToken = (String) store.openType(mCtx, String.class, KEY_SESSION);          	
                try {
                	// connect to server and get symptoms logs.
                	JSONFunctions userFunction = new JSONFunctions();
                	JSONObject json = userFunction.getSymptoms(
                			mUserID, mSessionToken, fields.getString("connection_id"));                                           
                	// check for login response                
                	if (json.getString(KEY_SUCCESS) != null) {
                		//hide error message from user.
                		emptyErrorMessage();
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){
                			if(!json.isNull("symptoms")){
                				// get the array.
                				JSONArray jsonLogs = json.getJSONArray("symptoms");              			
                				// go through each item in the array.
	                			for(int i = jsonLogs.length() - 1; i >= 0; i--){
	                				String name = jsonLogs.getJSONObject(i).getString("symptom_name");
	                				String value = jsonLogs.getJSONObject(i).getString("symptom_level");
	                				jsonLogs.getJSONObject(i).getString("symptom_note");
	                				jsonLogs.getJSONObject(i).getString("symptom_id");
	                				// find the severity of the symptom.   
	                				if(value.equals("1")){
	                					value = "Mild";
	                				} else if(value.equals("2")){
	                					value = "Average";
	                				} else if(value.equals("3")){
	                					value = "Severe";
	                				}               				
	                				patientsDataLog(name, value, dialogTable);
	                			} 
                			} else {
                                simpleDialog("No data logged.");
                			}            			
                		}else{
                			//let the user know there was an error.
                            simpleDialog("Error Accessing Database.");
                		}                		
                     }
                 } catch (Exception e) {
                	 //TODO better exception handling.
                     e.printStackTrace();
                     // let the user know there was an error.
                     simpleDialog("Network Connection Error.");
                 }
                 hideProgressDialog();
    		}                  	
    	}).start();		
    }  
    /**
     *  Handle patients dataLog
     * @param name
     * @param value
     * @param table
     */
    private void patientsDataLog(
    	final String name,
		final String value,
		final TableLayout table){
    	runOnUiThread(new Runnable() {
			public void run() {
				// New TextView to hold the log.
		      	TextView patientLogText = new TextView(mCtx);	      	
		      	TableRow row = new TableRow(mCtx);
		      	// Set the text to the text view.
		    	patientLogText.setText(asUpperCaseFirstChar(name) + ": " + value);
		    	// add views to the row
		    	row.addView(patientLogText); 
		    	row.setPadding(10, 10, 0, 10);
		    	// add to table.
		    	table.addView(row);
			}
		});
    }  
    /**
     * returns the string, the first char uppercase
     *
     * @param target
     * @return String
     */
    public final static String asUpperCaseFirstChar(final String target) {

        if ((target == null) || (target.length() == 0)) {
            return target; 
        }
        return Character.toUpperCase(target.charAt(0))
                + (target.length() > 1 ? target.substring(1) : "");
    }
    /**
     * Get Patient log for doctors. 
     * @param dialogTable
     * @param fields
     */
    public void getPatientLog(final TableLayout dialogTable, final JSONObject fields){
    	
    	new Thread(new Runnable() {
    		@Override
            public void run() {
    			// show progress dialog.
            	showProgressDialog();            	
    			// get data from local storage.
                StoreData store = new StoreData();
                // get user id from local storage
                mUserID = (String) store.openType(mCtx, String.class, KEY_UID);
                // get session token from local storage
                mSessionToken = (String) store.openType(mCtx, String.class, KEY_SESSION);              
                runOnUiThread(new Runnable() {
    				public void run() {
            			//clear table first.
    					dialogTable.removeAllViews();
    				}
    			});              
                try{
                	// get patient logs from server.
                	JSONFunctions userFunction = new JSONFunctions();
                	final JSONObject json = userFunction.getPatientLog(
                			mUserID, mSessionToken, fields.getString("connection_id"));                             
                	// check for login response               	
                	if (json.getString(KEY_SUCCESS) != null) {
                		// check if either of the returned json is null.
                		if(!json.isNull("logList") && !json.isNull("dataTypeList")){               			
                			// get JSON arrays.
	                		JSONArray jsonLogs = json.getJSONArray("logList");
	                        JSONArray jsonTypes = json.getJSONArray("dataTypeList");	                		
	                		String res = json.getString(KEY_SUCCESS);
	                		if(Integer.parseInt(res) == 1){	                			
	                			// setup array list.
	                			final ArrayList<String> logTypeStringArray = new ArrayList<String>();
	                			ArrayList<String> logTypeIdArray = new ArrayList<String>();                			
	                			// add the type names to a string array.
	                			for(int n = 0; n < jsonTypes.length(); n++){
	                				String name = jsonTypes.getJSONObject(n).getString("datalog_type_name");
	                				//convert the first character to uppercase.
	                				name = name.substring(0, 1).toUpperCase() + name.substring(1);                				
	                				logTypeStringArray.add(name);
	                				// get the id numbers in the same order as the names ->used for adding log.
	                				logTypeIdArray.add(jsonTypes.getJSONObject(n).getString("datalog_type_id"));
	                			}            				                			
	                			String type = "";	                				                				                			
	                			// go through all logs
	            				for(int i = jsonLogs.length()-1; i >= 0; i--){
	            					//go through each type of log
	            					for(int n = 0; n < jsonTypes.length(); n++){
	            						// if log type in logs array matches types array, then we know what type	
	            						if(jsonLogs.getJSONObject(i).getString(
	            								"datalog_type_id").equals(
	            										jsonTypes.getJSONObject(n).getString("datalog_type_id"))){
	            							type = jsonTypes.getJSONObject(n).getString("datalog_type_name");
	            						}
	            					}
	            					// get data log values.
	            					String value = jsonLogs.getJSONObject(i).getString("datalog_value");
	            					jsonLogs.getJSONObject(i).getString("datalog_note");
	            					jsonLogs.getJSONObject(i).getString("datalog_id");
	            					// pass values to handler.
	            					patientsDataLog(type, value, dialogTable); 	           					                		
	            				}                 			
	                		}else{
	                			//let the user know there was an error.
								simpleDialog("Error Accessing Database.");
	                		}  	
                		} else {
							simpleDialog("No data logged.");
                		}
                     }
                 } catch (Exception e) {
                	 //TODO better exception handling.
                     e.printStackTrace();
                     // let the user know there was an error.
                     simpleDialog("Network Connection Error.");
                 }
                 hideProgressDialog();
    		}                  	
    	}).start();	
	}
    /**
     * Refresh the layout.
     */
    private void refresh(){
		runOnUiThread(new Runnable() {
			public void run() {
				//clear contest of current view.
				mConnectionTable.removeAllViews();
				// check what sort of user they are.
				if("connections".equalsIgnoreCase(mUserType)){
					getConnections();
				} else if ("doctors".equalsIgnoreCase(mUserType)){
					getDoctors();
				}
            }
		});  
    }
    /**
     * Dismiss the progress dialog.
     */
    private void hideProgressDialog(){
    	runOnUiThread(new Runnable() {
            public void run() {
            	// hide progress spinner now that thread is finished.
            	//progressSpinner.setVisibility(View.INVISIBLE);
            	mLoadingDialog.dismiss();

            }
        });
    }
    /**
     * Create a progress dialog.
     */
    private void showProgressDialog(){
    	runOnUiThread(new Runnable() {
            public void run() {
            	// show progress spinner to let the user know it's working.
            //	progressSpinner.setVisibility(View.VISIBLE);
            	mLoadingDialog = new ProgressDialog(mCtx);
                mLoadingDialog.setTitle("");
                mLoadingDialog.setMessage("Loading. Please wait...");
            	mLoadingDialog.show();

            }
        });
    }
    /**
     * This is the help dialog for displaying help information.
     * @param message
     */
    private void helpDialog(final String message){		
		// new dialog
		final Dialog dialog = new Dialog(mCtx);
		dialog.setContentView(R.layout.popup);
		dialog.setTitle("Help options");	
		TableRow noteRow = new TableRow(mCtx);
      	TextView noteTx = new TextView(mCtx);
      	// add message to dialog.
      	noteTx.setText(message);
      	noteTx.setLayoutParams(new TableRow.LayoutParams(
      			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
      	// add views to the row
      	noteRow.addView(noteTx);   	 
      	noteRow.setPadding(10, 10, 0, 10);    
      	TableLayout dialogTable = (TableLayout) dialog.findViewById(R.id.dialogTable);    
      	// add the row to the table layout
      	dialogTable.addView(noteRow);			
		Button dialogButton = (Button) dialog.findViewById(R.id.dismiss);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();	
	}
    /**
     * Empty the error message.
     */
    private void emptyErrorMessage(){
    	runOnUiThread(new Runnable() {
			public void run() {
				mGetPatientsErrorMsg.setText("");
             	mGetPatientsErrorMsg.setVisibility(View.INVISIBLE);
            }
		});
    }
    /**
     * Show the error message
     * @param error
     */
    private void errorMessage(final String error){
    	runOnUiThread(new Runnable() {
			public void run() {
				mGetPatientsErrorMsg.setText(error);
             	mGetPatientsErrorMsg.setVisibility(View.VISIBLE);
            }
		});
    }    
}
